package com.tc.dispatch.web.schedule.order;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import com.tc.dispatch.gsservice.basic.common.regulation;
import com.tc.dispatch.gsservice.basic.common.tcdate;
import com.tc.dispatch.gsservice.ejb.GSServiceLocal;
import com.tc.dispatch.gsservice.exception.GSException;
import com.tc.dispatch.gsservice.model.OrderSumMain;
import com.tc.dispatch.gsservice.model.OrderSumSub;
import com.tc.dispatch.web.gsservice.gsHelper;
import com.tc.dispatch.web.model.combinedOrder;
import com.tc.dispatch.web.util.DateJsonValueProcessor;
import com.tc.dispatch.web.util.tools;

public class orderCaiLiaoIndex extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public orderCaiLiaoIndex() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");
		if (action == null)
			action = "";

		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		HttpSession sess = request.getSession();
		OrderSumMain osm = new OrderSumMain();
		OrderSumMain osmDef = new OrderSumMain();
		String pos="-1";
		if(sess.getAttribute("position")!=null)
			{
				pos=(String)sess.getAttribute("position");
			};
		if (action.equals("list")) {
			if(request.getParameter("subAction")!=null&&request.getParameter("subAction").equals("again"))
			{
				String id=request.getParameter("id");
				String type=request.getParameter("type");
				try{
				if(id!=null&&!id.equals(""))
				{
					if(type.equals("0"))
					{
						osmDef=(OrderSumMain)gss.findOrderSumMain(" where id='"+id+"' and type="+type).get(0);
						osm=(OrderSumMain)gss.findOrderSumMain(" where month1="+osmDef.getMonth1()+" and year1="+osmDef.getYear1()+" and type=1 and spec='"+osmDef.getSpec()+"'").get(0);
					}
					else
					{
						osm=(OrderSumMain)gss.findOrderSumMain(" where id='"+id+"' and type="+type).get(0);
						osmDef=(OrderSumMain)gss.findOrderSumMain(" where month1="+osm.getMonth1()+" and year1="+osm.getYear1()+" and type=0 and spec='"+osm.getSpec()+"'").get(0);
					}
					sess.setAttribute("position", "3");
					//List processList = (List) sess.getAttribute("processList");
					//OrderSumSub oss = (OrderSumSub) processList.get(0);
					int osmid = osm.getId().intValue();
					List processList = gss.findOrderSumSub("where ordersumid=" + osmid
							+ " order by processPos");
					sess.setAttribute("processList", processList);
					osmid=osmDef.getId().intValue();
					List processListDef = gss.findOrderSumSub("where ordersumid=" + osmid
							+ " order by processPos");
					sess.setAttribute("processListDef", processListDef);
					
				}
				}
				catch(GSException e)
				{
					System.out.println("GSException:"+e.getMessage());
					
				}
				sess.removeAttribute("OrderSumMain");
				sess.setAttribute("OrderSumMain", osm);
				
				
				sess.removeAttribute("OrderSumMainDef");
				sess.setAttribute("OrderSumMainDef", osmDef);
			}
			else
			if(Integer.parseInt(pos)==-1)//表示 刚开始
			{
			String dateFrom = request.getParameter("dateFrom");
			String dateTo = request.getParameter("dateTo");
			Date dateF;
			Date dateT;
			String spec = request.getParameter("spec");
			String ssign = request.getParameter("ssign");
			String plate = request.getParameter("plate");

			if (spec == null)
				spec = "";
			if (ssign == null)
				ssign = "";
			if (plate == null)
				plate = "";
			if (dateFrom == null || dateFrom.equals(""))
				dateF = Calendar.getInstance().getTime();
			else
				dateF = tools.stringToDate(dateFrom);
			if (dateTo == null || dateTo.equals(""))
				dateT = Calendar.getInstance().getTime();
			else
				dateT = tools.stringToDate(dateTo);
			dateF = tcdate.getStartFromDate(dateF);
			dateT = tcdate.getEndFromDate(dateT);
			String transnum = request.getParameter("transnum");
			if (transnum == null)
				transnum = "";
			String ordernum = request.getParameter("ordernum");
			if (ordernum == null||ordernum.equals(""))
				ordernum = "0";
			String ordercost = request.getParameter("price");
			if (ordercost == null||ordercost.equals(""))
				ordercost = "0";
			System.out.println("ordercost:"+ordercost);
			
			osm.setSsign(ssign);
			osm.setSpec(spec);
			osm.setPlate(plate);
			osm.setTransnum(transnum);
			osm.setOrdernum(Integer.valueOf(ordernum));
			osm.setType((byte)1);
			osm.setOrdercost(new Float(Float.parseFloat(ordercost)/regulation.fee));
			
			
			osmDef.setSsign(ssign);
			osmDef.setSpec(spec);
			osmDef.setPlate(plate);
			osmDef.setTransnum(transnum);
			osmDef.setOrdernum(Integer.valueOf(ordernum));
			osmDef.setType((byte)0);
			osmDef.setOrdercost(new Float(Float.parseFloat(ordercost)/regulation.fee));
			System.out.println("osmDef.fee:"+osmDef.getOrdercost());
			Date date1;
			String dateS=request.getParameter("date1");
			if (dateS == null || dateS.equals(""))
				date1 = Calendar.getInstance().getTime();
			else
				date1 = tools.stringToDate(dateS);
			int month1=tcdate.getMonth(date1);
			int year1=tcdate.getYear(date1);
			osm.setDate1(date1);
			osm.setMonth1(new Integer(month1));
			osm.setYear1(new Integer(year1));
			
			osmDef.setDate1(date1);
			osmDef.setMonth1(new Integer(month1));
			osmDef.setYear1(new Integer(year1));

			try {

				osm = gss.getERPKaimo(osm);
				sess.removeAttribute("OrderSumMain");
				sess.setAttribute("OrderSumMain", osm);
				
				osmDef = gss.getERPKaimo(osmDef);
				
				int ordersumid = gss.createOrderSumMain(osm);
				int ordersumiddef = gss.createOrderSumMain(osmDef);
				
				sess.removeAttribute("OrderSumMainDef");
				sess.setAttribute("OrderSumMainDef", osmDef);
				sess.setAttribute("position", "0");
				sess.setAttribute("task", "started");
				
			} catch (GSException e) {
				System.out.println("GSException:"+e.getMessage());
				out.print("{success:false, data:'false'}");
			}
			}
			else
			{
				osm=(OrderSumMain)sess.getAttribute("OrderSumMain");
				osmDef=(OrderSumMain)sess.getAttribute("OrderSumMainDef");
			}
			JSONObject json = new JSONObject();
			JsonConfig cfg = new JsonConfig();
			cfg.registerJsonValueProcessor(java.util.Date.class,
					new DateJsonValueProcessor());
			cfg.registerJsonValueProcessor(java.sql.Date.class,
					new DateJsonValueProcessor());

			// BeanUtils.copyProperties();
			json.put("totalProperty", new Integer(1));
			List ret=new ArrayList();
			combinedOrder corder=new combinedOrder();
			
			ret.add(corder);

			JSONArray arr = JSONArray.fromObject(ret.toArray(),cfg);
             json.put("root", arr);
            
			//json.put("osm", osm);
			response.getWriter().print(json);
		}
		
		
		else if(action.equals("update"))
		{
		
			osm =(OrderSumMain) sess.getAttribute("OrderSumMain");
			osmDef=(OrderSumMain) sess.getAttribute("OrderSumMainDef");
			
			String spec_yz=request.getParameter("spec_yz");
			String spec_yz2=request.getParameter("spec_yz2");
			String ssign_yz=request.getParameter("ssign_yz");
			String ssign_yz2=request.getParameter("ssign_yz2");
			String factory=request.getParameter("factory");
			String factory2=request.getParameter("factory2");
			try{
			osm.setSpec_yz(spec_yz);
			osm.setSsign_yz(ssign_yz);
			osmDef.setSpec_yz(spec_yz2);
			osmDef.setSsign_yz(ssign_yz2);
			osm.setFactory(Integer.valueOf(factory));
			osmDef.setFactory(Integer.valueOf(factory2));
			sess.removeAttribute("OrderSumMain");
			sess.setAttribute("OrderSumMain", osm);
			
			
			sess.removeAttribute("OrderSumMainDef");
			sess.setAttribute("OrderSumMainDef", osmDef);
			}
			catch(Exception e)
			{
				out.print("{success:false, data:'false'}");
			}
			out.print("{success:true, data:'sucess'}");
			
		}
		out.flush();
		out.close();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
